package edu.udo.sopra10.chaturaji.gui;

import java.util.HashMap;

import org.apache.batik.swing.JSVGCanvas;
import org.apache.batik.swing.svg.SVGDocumentLoaderEvent;
import org.apache.batik.swing.svg.SVGDocumentLoaderListener;
import org.w3c.dom.svg.SVGDocument;

/**
 * Panel to display a die.
 * 
 * The class uses CSS class names to apply settings to the underlaying vector
 * graphics.
 * 
 * @author Patrick Westerhoff
 */
public class DiePanel extends JSVGCanvas
{
	private static final long serialVersionUID = 3865192789787424484L;
	private static final HashMap<Byte, String> DICE = new HashMap<Byte, String>( 6 );
	
	private byte dieValue;
	
	static
	{
		DICE.put( (byte) 1, "d1" );
		DICE.put( (byte) 2, "d2" );
		DICE.put( (byte) 3, "d3" );
		DICE.put( (byte) 4, "d4" );
		DICE.put( (byte) 5, "d5" );
		DICE.put( (byte) 6, "d6" );
	}
	
	/**
	 * Constructs a die panel with the given value.
	 * 
	 * @param value die value to display.
	 */
	public DiePanel ( byte value )
	{
		this.dieValue = -1;
		
		this.addSVGDocumentLoaderListener( new SVGPieceLoaderListener() );
		this.setEnableZoomInteractor( true );
		this.setBackground( null );
		
		this.loadSVGDocument( getClass().getResource( "/die.svg" ).toString() );
		setSize( 50, 50 );
	}
	
	/**
	 * Constructs a die panel.
	 * 
	 */
	public DiePanel ()
	{
		this( (byte) -1 );
	}
	
	/**
	 * Updates the displayed SVG with the internal {@link SVGDocument}.
	 * 
	 */
	public void updateDisplay ()
	{
		this.stopThenRun( new Runnable()
			{
				@Override
				public void run ()
				{
					installSVGDocument( svgDocument );
				}
			} );
	}
	
	/**
	 * Sets the displayed die value.
	 * 
	 * @param value die value to display.
	 */
	public void setDieValue ( byte value )
	{
		dieValue = value;
		
		if ( svgDocument == null )
			return;
		
		svgDocument.getDocumentElement().setAttribute( "class", DICE.get( value ) );
		this.updateDisplay();
	}
	
	
	/**
	 * Simple SVGDocumentLoaderListener that only implements
	 * {@link SVGDocumentLoaderListener#documentLoadingCompleted} and applies
	 * previously set class names or transformations to the correct element
	 * nodes.
	 * 
	 * @author Patrick Westerhoff
	 */
	private class SVGPieceLoaderListener implements SVGDocumentLoaderListener
	{
		@Override
		public void documentLoadingCancelled ( SVGDocumentLoaderEvent event )
		{
		}
		
		@Override
		public void documentLoadingCompleted ( SVGDocumentLoaderEvent event )
		{
			SVGDocument document = event.getSVGDocument();
			
			if ( dieValue != -1 )
				document.getDocumentElement().setAttribute( "class", DICE.get( dieValue ) );
		}
		
		@Override
		public void documentLoadingFailed ( SVGDocumentLoaderEvent event )
		{
		}
		
		@Override
		public void documentLoadingStarted ( SVGDocumentLoaderEvent event )
		{
		}
	}
}
